package cn.bonoon.kernel.web.components;

import static cn.bonoon.kernel.util.StringHelper.isEmpty;
import cn.bonoon.kernel.descriptors.UIPropertyAccessor;
import cn.bonoon.kernel.web.annotations.components.AsRadio;
import cn.bonoon.kernel.web.annotations.components.SelectorOption;
import cn.bonoon.kernel.web.html.UIPropertyBuilder;
import cn.bonoon.kernel.web.html.form.ComponentPropertyParser;

public class RadioComponent extends AbstractComponent{

	private final AsRadio asRadio;
	public RadioComponent(ComponentPropertyParser property, UIPropertyAccessor accessor, AsRadio asRadio) {
		super(property, accessor);
		this.asRadio = asRadio;
	}

	@Override
	protected void parser(UIPropertyBuilder builder) {
		StringBuilder html = builder.getInitHtml();
		html.append("<table border='0' cellspacing='0' cellpadding='0' style='padding:0;margin:0;'><tr>");
		int l = 0, c = asRadio.column();
		boolean isNum = accessor.isNumber();
		for (int i = 0; i < asRadio.value().length; i++) {
			SelectorOption opt = asRadio.value()[i];
			String v = opt.value(), n = opt.name();
			if (isEmpty(v)){
				v = Integer.toString(i);
			}else if (isEmpty(n)){
				n = v;
			}
//			String fn = accessor.getName();
			String radioId = componentId + '-' + i;
			html.append("<td align='left'><input type='radio' name='").append(componentName);
			html.append("' style='vertical-align:middle;margin-top:-2px;margin-bottom:1px;' id='").append(radioId);
			html.append("' value='").append(v);
			html.append("' #if($").append(builder.getBindedName());
			html.append('.').append(componentName);
			html.append(" == ");
			if(isNum){
				html.append(v);
			}else{
				html.append('"').append(v).append('"');
			}
			html.append(")checked='checked'#end><label for='").append(radioId);
			html.append("'>").append(n).append("</label></td>");
			if (c > 0) {
				if (l < c) {
					l++;
				} else {
					l = 0;
					html.append("</tr><tr>");
				}
			}
		}
		html.append("</tr></table>");
	}

}
